var vip_prefix = ["http://api.51ckm.com/jx.php?url=", "http://api.nepian.com/ckparse/?url="];
var curTab = null;
/*
chrome.browserAction.onClicked.addListener(function(tab) {
    var prefix = "http://api.51ckm.com/jx.php?url=";
    var vipUrl = prefix + tab.url;
    chrome.tabs.executeScript(tab.id, {code : "window.location.href='" + vipUrl + "'"});
});
*/

var isJson = function(obj){
    var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
    return isjson;
}
/*
*使用JS跨域的方案，向服务器请求数据
*/
function fetchData() {
    var script = document.createElement("script");
    var url = "https://git.oschina.net/taugin/browser_plugins/raw/master/code/vipplayer/config.js";
    script.src = url;
    script.type = "text/javascript";
    var head = document.getElementsByTagName("head");
    if(head && head[0]) {
        head[0].appendChild(script);
    }
}

// 回调配置数据
function config(data) {
    if (data != null && isJson(data)) {
        vip_prefix = data.vipprefix;
        if (vip_prefix != null && vip_prefix instanceof Array && vip_prefix.length > 0) {
            document.body.innerHTML = "<h3 style='color:red'>API配置</h3>";
            updatePopup();
        }
    }
}

// 更新弹出框
function updatePopup() {
    var item = null;
    for (var index = 0; index < vip_prefix.length; index++) {
        if (vip_prefix[index] != null && vip_prefix[index].trim() != "") {
            item = document.createElement("h3");
            item.innerText = "VIP播放" + (index + 1);
            item.id = vip_prefix[index];
            item.className="item";
            item.onclick = playvip;
            document.body.appendChild(item);
        }
    }
}

// 替换当前播放地址
function playvip(event) {
    var prefix = this.id;
    if (curTab != null) {
        playVip(prefix, curTab.url);
    }
    window.close();
}

function playVip(prefix, videoUrl) {
    var vipUrl = prefix + videoUrl;
    chrome.tabs.executeScript(curTab.id, {code : "window.location.href='" + vipUrl + "'"});
}

window.onload = function() {
    updatePopup();
    // 通过JSONP方式获取配置信息
    fetchData();
    // 获取当前的tab页面对象
    chrome.tabs.query({active:true}, function (tabs){
        curTab = tabs[0];
    });
};